// import ajax from 'uni-ajax'
import env from '@/env'
import ajax from 'uni-ajax';
import { useAuthStore } from '@/store/index';
import { errorCode } from '@/utils/errorCode';
import { encryptBase64, encryptWithAes, generateAesKey, decryptWithAes, decryptBase64 } from '@/utils/crypto';
import { encrypt, decrypt } from '@/utils/jsencrypt';
import { HttpStatus } from '@/utils/RespEnum';

const encryptHeader = 'encrypt-key';
const instance = ajax.create({
  baseURL: env.baseURL,
  header: {
    // Authorization: `Bearer ${store.state.userInfo.token}`,
    // post: {
    //   'Content-Type': 'application/json'
    // }
  },
  timeout: 50000
});

// 请求拦截器
instance.interceptors.request.use(
  config => {
    const authStore = useAuthStore();
    const token = authStore.userInfo.token;
	// 是否需要加密
	const isEncrypt = config.header?.isEncrypt == true;
    if (token) {
		config.header = {
			...config.header,
			'Authorization': `Bearer ${token}`,
			'clientid': env.VITE_APP_CLIENT_ID,
		}
    }
	if (env.VITE_APP_ENCRYPT) {
	  // 当开启参数加密
	  if (isEncrypt && (config.method == 'POST' || config.method == 'PUT')) {
		// 生成一个 AES 密钥
		const aesKey = generateAesKey();
		config.header[encryptHeader] = encrypt(encryptBase64(aesKey));
		config.data = typeof config.data == 'object' ? encryptWithAes(JSON.stringify(config.data), aesKey) : encryptWithAes(config.data, aesKey);
	  }
	}
	// FormData数据去请求头Content-Type
	// if (config.data instanceof FormData) {
	//   delete config.headers['Content-Type'];
	// }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 响应拦截器
instance.interceptors.response.use(
  res => {
	if (env.VITE_APP_ENCRYPT == 'true') {
		// 加密后的 AES 秘钥
		const keyStr = res.headers[encryptHeader];
		// 加密
		if (keyStr != null && keyStr != '') {
		  const data = res.data;
		  // 请求体 AES 解密
		  const base64Str = decrypt(keyStr);
		  // base64 解码 得到请求头的 AES 秘钥
		  const aesKey = decryptBase64(base64Str.toString());
		  // aesKey 解码 data
		  const decryptData = decryptWithAes(data, aesKey);
		  // 将结果 (得到的是 JSON 字符串) 转为 JSON
		  res.data = JSON.parse(decryptData);
		}
	}
	// 未设置状态码则默认成功状态
	const code = res.data.code || HttpStatus.SUCCESS;
	// 获取错误信息
	const msg = errorCode[code] || res.data.msg || errorCode['default'];

    const data = res.data
    if (data && data.code == 401) {
		uni.showToast({
		  title: '登录认证过期，请重新登录！',
		  icon: 'none'
		})
		setTimeout(() => {
		  uni.redirectTo({
			url: '/pages/login/index'
		  })
		}, 1000);
      return
    }
    return res
  },
  error => {
    uni.showToast({
      title: 'error'
    })
    return error
  }
);

export default instance;
